<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\admin\controller;
use app\admin\model\Admintype;
use app\admin\model\Campus;
use app\admin\validate\AdminValidate;
use think\Db;
use app\admin\model\Admin;

class AdminController extends CommonController
{
    /**
     * 账号密码登录
     * @return bool
     */
    public  function studentLogin(){
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[34578]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('ew_admin')->where('username',$phone)->find();
                if(empty($username)){
                    return json(['status'=>3,'msg'=>'没有此用户']);
                }else{
                    if($username['password'] != $pass){
                        return json(['status'=>4,'msg'=>'密码错误']);
                    }else{
                        return json(['status'=>5,'msg'=>'成功登陆']);
                    }
                }
            }
        }else{
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }

    }

    /**
     * 手机验证码登录
     * @return bool
     */
    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是老手机发送 2是新手机发送)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */

    public  function getPhoneCode(){
        $type = $_POST['type'];
        if($type == 1){
            $phone = session('loginSession')['phone'];
        }else{
            $phone = $_POST['phone'];
        }
        if(!preg_match("/^1[34578]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $num = rand(100000,999999);
        $username = Db::table('ew_admin')->where('phone',$phone)->find();
        if(empty($username) && $type==1){
            return json_encode(['status'=>0,'msg'=>'没有此手机号码用户']);
        }
        if(!empty($username) && $type==2){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码用户']);
        }

        $sendres = $this->duaxin($phone,$num);
        if($sendres['code'] != '00000'){
            return json_encode(['status'=>3,'msg'=>$sendres['msg']]);
        }else{
            //=============================
            $isset = Db::table('ew_phonecode')->where('phone',$phone)->find();
            if($isset){
                $res = Db::table('ew_phonecode')->where('phone',$phone)->update(['code'=>md5($num),'time2'=>time(), 'status' => 0]);
            }else{
                $res = Db::table('ew_phonecode')->insert(['phone'=>$phone,'code'=>md5($num),'time2'=>time()]);
            }
            if(!$res){
                return json_encode(['status'=>31,'msg'=>'数据库操作失败']);
            }
            //===============================================
            return json_encode(['status'=>200,'msg'=>md5($num)]);
        }
    }


    public function authLogin()
    {
        //header("Access-Control-Allow-Origin:*");
//        echo 1;die;

        $username = input('UserName');
        $password = input('PassWord');
        if (isNotNull($username) && isNotNull($password)) {
            $admin = Db::table('ew_admin')->where(["username" => $username, "password" => $password])->find();

            if ($admin) {
                session('loginSession', $admin);
                return 1;
            } else {
                session("loginSession", null);
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 退出
     */
    public function authLogout()
    {
        session("loginSession", null);
        return 1;
    }

    /**
     * 个人信息
     */
    public function personinfo_manage()
    {
        $admin = Db::table('ew_admin')->where('id', session('loginSession')['id'])->find();
        $this->assign('admin', $admin);
        return $this->fetch('admin/personinfo');
    }

    /**
     * 修改个人信息
     */
    public function personal_setting()
    {
        $admin = Db::table('ew_admin')->where('id', session('loginSession')['id'])->find();
        $admin['regtime'] = substr($admin['regtime'], 0, 10);
        $this->assign('admin', $admin);
        return $this->fetch('admin/setting');
    }

    public function updateSetting()
    {
        $id = $_POST['id'];
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        $data = array();
        $data['relname'] =trim($_POST['name'],' ');
        if(empty($_POST['name'])){return json_encode(['status'=>0,'msg'=>'名字不能为空']);}
        if(!empty($_FILES['pic']['tmp_name'])){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$_FILES['pic']['name'])[1];
            $_FILES['pic']['name'] = $rand . '.' .$exe;
            //=======================
            if(move_uploaded_file($_FILES['pic']['tmp_name'],"{$dir}/mang/avatar/{$_FILES['pic']['name']}")){
                $data['avatar'] = "{$url}/mang/avatar/{$_FILES['pic']['name']}";
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }
        $data['regtime'] = date('Y-m-d H:i:s');
        $res = Db::table('ew_admin')->where('id',$id)->update($data);
        if($res){
            if(!empty($_FILES['pic']['tmp_name'])) {
                session('loginSession')['avatar'] = $data['avatar'];
            }
            return json_encode(['status'=>1,'msg'=>'修改成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'修改失败']);
        }
    }

    /**
     * 修改密码
     */
    public function change_password()
    {
        $admin = Db::table('ew_admin')->where('id', session('loginSession')['id'])->find();
        $this->assign('admin', $admin);
        return $this->fetch('admin/password');
    }

    public function updatePassword()
    {
        $registrationModel = M("Admin");
        $admin = Db::table('ew_admin')->where('id', session('loginSession')['id'])->find();
        if ($_POST['oldPassword'] != $admin['password']) {
            $returnData['status'] = 0;
            $returnData['msg'] = '原密码输入不正确';
            return json_encode($returnData);
        } else if ($_POST['password'] != $_POST['surePassword']) {
            $returnData['status'] = 0;
            $returnData['msg'] = '两次密码输入不一样';
            return json_encode($returnData);
        }
        //===============
        $phone = session('loginSession')['phone'];
        //=============================================================
        $res = Db::table('ew_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($_POST['usercode'] == ''){
            return json_encode(['status'=>0,'msg'=>'验证码不能为空']);
        }
        $code = md5($_POST['usercode']);
        if($code != $res['code']){
            return json_encode(['status'=>0,'msg'=>'验证码错误']);
        }
        if($res['status'] != 0){
            return json_encode(['status'=>0,'msg'=>'验证码已使用，请重新发送']);
        }
        $now = time();
        if($now - $res['time2'] >= 601){
            return json_encode(['status'=>0,'msg'=>'验证码超时']);
        }
        Db::table('ew_phonecode')->where('phone',$phone)->update(['status'=>1]);
        //===============
        unset($_POST['oldPassword']);
        unset($_POST['surePassword']);
        unset($_POST['usercode']);
        $registrationModel->update($_POST);
        $returnData['status'] = 1;
        $returnData['msg'] = "修改成功";
        return json_encode($returnData);

    }

    /**
     * 修改手机号——1：给旧手机发送验证码
     * 参数：
     * @return string
     */
    public function changephone_old()
    {
        $phone = session('loginSession')['phone'];
//        $one = substr($phone,0,3 );
//        $two = substr($phone,7,4 );
//        $phone = $one . '****' . $two;
        $this->assign('phone', $phone);
        return $this->fetch("admin/changephone_old");
    }
    /**
     * 修改手机号——2：给旧手机发送验证码
     * 参数：
     * @return string
     */
    public function changephone_old_yzm()
    {
        $phone = session('loginSession')['phone'];
        //=============================================================
        $res = Db::table('ew_phonecode')->where('phone',$phone)->find();
        //=============================================================
        $code = md5($_POST['usercode']);
        if($code != $res['code']){
            return json_encode(['status'=>0,'msg'=>'验证码错误']);
        }
        if($res['status'] != 0){
            return json_encode(['status'=>0,'msg'=>'验证码已使用，请重新发送']);
        }
        $now = time();
        if($now - $res['time2'] >= 601){
            return json_encode(['status'=>0,'msg'=>'验证码超时']);
        }
        Db::table('ew_phonecode')->where('phone',$phone)->update(['status'=>1]);
        return json_encode(['status'=>200,'msg'=>'ok']);
    }
    /**
     * 修改手机号——3：新手机发送验证码
     * 参数：
     * @return string
     */
    public function changephone_new()
    {
        return $this->fetch("admin/changephone_new");
    }
    /**
     * 修改手机号——4：提交新手机
     * 参数：
     * @return string
     */
    public function changephone_new_yzm()
    {
        $phone = trim($_POST['phone'],' ');
        $code = trim($_POST['usercode'],' ');
        if($phone == "" || $code == ""){
            return json_encode(['status'=>0,'msg'=>'手机号和验证码不能为空']);
        }
        $username2 = Db::table('ew_admin')->where('phone',$phone)->find();
        if(!empty($username2)){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码用户']);
        }
        //=============================================================
        $res = Db::table('ew_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if(empty($res)){
            return json_encode(['status'=>0,'msg'=>'不是同一个手机号']);
        }
        $code = md5($code);
        if($code != $res['code']){
            return json_encode(['status'=>0,'msg'=>'验证码错误']);
        }
        if($res['status'] != 0){
            return json_encode(['status'=>0,'msg'=>'验证码已使用，请重新发送']);
        }
        $now = time();
        if($now - $res['time2'] >= 601){
            return json_encode(['status'=>0,'msg'=>'验证码超时']);
        }
        $id = session('loginSession')['id'];
        $res2 = Db::table('ew_admin')->where('id',$id)->update(['phone'=>$phone]);
        if($res2){
            $admin = Db::table('ew_admin')->where('id',$id)->find();
            session('loginSession', null);
            session('loginSession', $admin);
            return json_encode(['status'=>200,'msg'=>'更换成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'更新失败']);
        }

    }
    /**
     * 获得数据
     * Author ghostsf
     * Blog www.ghostsf.com
     */
    public function getDatas()
    {
//        $rows = $_POST['rows'];
//        $page = $_POST['page'];
//        $start = "";
//        if (empty($_POST['regtime'])) {
//            $start = 0;
//            unset($_POST['regtime']);
//        } else {
//            $start = $_POST['regtime'];
//            unset($_POST['regtime']);
//        };
//        $searchPath = $this->getDataByCampusid($_POST);
//        if (session("loginSession")['typeid'] == 0) {
//            unset($searchPath["campusid"]);
//        } else {
//            $searchPath['admin.campusid'] = $searchPath["campusid"];
//            unset($searchPath["campusid"]);
//        }
//        $class = Admin::with("campus")->where($searchPath)->where('regtime', '>', $start)->limit($rows * ($page - 1), $rows)->select();
//
//        $total = Admin::with("campus")->where($searchPath)->where('regtime', '>', $start)->count();
//        $data['total'] = $total;
//        $data['rows'] = $class;
//        return json_encode($data);
    }

    public function addadmin()
    {
        $this->assign('user', session('loginSession')['typeid']);
        return $this->fetch("admin/add");
    }

    public function insert()
    {
        if (isNotNull(session('loginSession')['campusid'])) {
            $_POST['campusid'] = session('loginSession')['campusid'];
        }
        $registrationModel = M("Admin");
        $validata = new AdminValidate();
        if (!$validata->check($_POST)) {
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        } else {
            $_POST['regtime'] = date("Y-m-d H:i:s");
            $_POST['typeid'] = 1;
            $registrationModel->insert($_POST);
            $returnData['status'] = 1;
            $returnData['msg'] = "成功";
            return json_encode($returnData);
        }
    }

    public function updateadmin()
    {
        $id = input('id', '');
//        $User = Admin::get($id);
//        $this->assign("user", $User);
//        $campus = Campus::all();
//        $this->assign('campus', $campus);
//        $this->assign('admin', session('loginSession')['typeid']);
//        return $this->fetch("admin/update");
    }

    public function update()
    {
        $registrationModel = M("Admin");
        $validata = new AdminValidate();
        if (!$validata->check($_POST)) {
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        } else {
            $registrationModel->update($_POST);
            $returnData['status'] = 1;
            $returnData['msg'] = "修改成功";
            return json_encode($returnData);
        }
    }

    public function deleteByIDs()
    {
        $ids = input('ids');
        $ids = rtrim($ids, ",");
        $map['id'] = array('in', $ids);
        $deleteinfo = Admin::where($map)->delete();
        if ($deleteinfo) {
            return json_encode(array("status" => 1, "msg" => "删除成功！"));
        } else {
            return json_encode(array("status" => 0, "msg" => "删除失败！"));
        }
    }

    /**
     * @return mixed
     */
    public function ghname()
    {
        $user = Db::name('campus')->where('id=1')->find();
        $this->assign("name", $user['campus_name']);
        $this->assign("id", $user['id']);
        return $this->fetch("admin/dd");
    }

    /**
     * @return string
     * @throws \think\Exception
     */

    public function mark()
    {
        $id = input("id");
        $name = trim(input("name"));

        M("campus")->where(["id" => $id])->update(["campus_name" => $name]);
        return json_encode(["status" => 1, "msg" => '修改成功']);
    }

    /**
     * 公告
     */
    public function gonggao()
    {
        $id = input('id');
        $user = Db::name('notice')->where("id={$id}")->find();
        $this->assign("user", $user);
        return $this->fetch("admin/gonggao");
    }

    /**
     * 公告列表页
     */
    public function gonggaolist()
    {
        $campusid = session("loginSession")['campusid'];
        $num = M("notice")->where(["campusid" => $campusid, "type" => '1', "status" => '1'])->count('id');
        $p=10;
        $max=ceil($num/$p);
        //$_POST
        if(!isset($_POST['p'])) $_POST['p']=1;
        if($_POST['p']<1){$_POST['p']=1;}
        if($_POST['p']>$max){$_POST['P']=$max;}
        $prev=$_POST['p']==1?1:$_POST['p']-1;
        $next=$_POST['p']==$max?$max:$_POST['p']+1;
        $start=($_POST['p']-1)*$p;

        $data = Db::name("notice")->where(["campusid" => $campusid, "type" => '1', "status" => '1'])->order("time desc")->limit("{$start},{$p}")->select();

        $this->assign("datas", $data);
        $this->assign("prev",$prev);
        $this->assign("next",$next);
        $this->assign("max",$max);
        return $this->fetch("admin/list");
    }

    /**
     * 公告列表页
     */

    /**
     * 修补alert
     */
    public function alertlog()
    {
        $ti=input("t");
        if($ti==1){
            $tishi="请选取表格";
        }elseif($ti==2){
            $tishi="导入成功";
        }elseif($ti==3){
            $tishi="只限上传excel表格！";
        }elseif($ti==4){
            $tishi="对不起，选取不能为空";
        }elseif($ti==5){
            $tishi="此功能暂时不对外开放<br/>例子：今天:8点半约张总吃饭";
        }
        $this->assign("ti",$tishi);
        return $this->fetch("admin/alert");
    }
 /**
     * 日历事件页面
     */

    public  function event()
    {
        if($_POST['gd']){
            $_POST['gd']=preg_replace('/GD/',"",$_POST['gd']);
        }
        $user=session("loginSession")['username'];
        $this->assign("user",$user);
        $data=Db::name("event")->where($_POST)->find();
        if($data!=null){
            $this->assign("id",$data['id']);
            $this->assign("content",$data['content']);
            $this->assign("gd",$_POST['gd']);
        }else{
            $this->assign("content","");
            $this->assign("id","");
            $this->assign("gd",$_POST['gd']);
        }

        return $this->fetch("admin/event");
    }

    /**
     * 添加事件  下面是完全版开放内容
     */
    public function addevent()
    {

        if($_POST['id']==null){
            $bool= Db::execute("insert into aew_event (date,day,content,username,gd)values(?,?,?,?,?)",[$_POST['date'],$_POST['day'],$_POST['content'],$_POST['username'],$_POST['gd']]);
            if($bool){
                $data['status']=1;
                $data['msg']="添加成功";

            }else{
                $data['status']=0;
                $data['msg']="添加失败";
            }

            return json_encode($data);
        }else{
            if($_POST["content"]==null){
                $bool=Db::name("event")->where('id',$_POST['id'])->delete();
                if($bool){
                    $data['status']=1;
                    $data['msg']="删除成功";

                }else{
                    $data['status']=0;
                    $data['msg']="删除失败";
                }
                return json_encode($data);
            }else{
                $id=$_POST['id'];
                unset($_POST['id']);
                $bool=Db::name("event")->where(['id'=>$id])->update($_POST);
                if($bool){
                    $data['status']=1;
                    $data['msg']="修改成功";

                }else{
                    $data['status']=0;
                    $data['msg']="修改失败";
                }
                return json_encode($data);
            }
        }

    }

    /** 查询当天有没有事情
     * @return string
     */

    public  function selectEvent()
    {

      $_POST['username']=session("loginSession")['username'];


       $data=Db::name('event')->group("gd")->where($_POST)->field('gd')->select();

        return json_encode($data);
    }


    public function detailEvent()
    {   $_POST['gd']=preg_replace('/GD/',"",$_POST['gd']);
        $_POST['username']=session("loginSession")['username'];
        $data=Db::name("event")->where($_POST)->find();

        $this->assign('data', $data);
        return $this->fetch("admin/details");
    }


}